package com.construction.api.domain.model.header;

import com.construction.api.enums.ResultEnum;
import com.construction.api.exception.BusinessException;
import com.construction.api.util.JwtTokenUtil;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author dybin
 * @Date: 2021/7/2 21:51
 */
@Data
@Component
@RequiredArgsConstructor
public class Header {

    private String token;

    @NonNull
    public static Header of(HttpServletRequest request, JwtTokenUtil jwtTokenUtil) {
        Header header = new Header();
        String desToken = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (ObjectUtils.isEmpty(desToken)) {
            throw BusinessException.of(ResultEnum.UNAUTHORIZED, "token不允许为空");
        }
        header.token = jwtTokenUtil.decrypt(desToken);
        return header;
    }
}
